﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace System.Web.Mvc
{
    public class PagedList<T> :List<T>,IPagedList
    {

        public int TotalCount
        {
            get;
            set;
        }

        public int TotalPages
        {
            get
            {
                if (this.TotalCount > 0)
                {
                    return (int)Math.Ceiling((double)this.TotalCount / (double)this.PageSize);
                }
                else
                {
                    return 0;
                }
            }
        }

        public int? PageIndex
        {
            get;
            set;
        }

        public int PageSize
        {
            get;
            set;
        }

        public bool IsPreviousPage
        {
            get
            {
                return (PageIndex ?? 1) > 1;
            }
        }

        public bool IsNextPage
        {
            get
            {
                return ((PageIndex ?? 1) * PageSize) < TotalCount;
            }
        }

        public PagedList(IQueryable<T> source, int index, int pageSize)
        {
            this.TotalCount = source.Count();
            this.PageSize = pageSize;
            this.PageIndex = index;
            this.AddRange(source.Skip((index - 1) * pageSize).Take(pageSize).ToList());
        }

    }

    public static class Pagination
    {
        public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int index, int pageSize)
        {
            return new PagedList<T>(source, index, pageSize);
        }

        public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int index)
        {
            return new PagedList<T>(source, index, 10);
        }
    }

}